﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Threading;
using System.Web;
using System.Web.Mvc;
using EC18_ESHOP.Models;
using Newtonsoft.Json;

namespace EC18_ESHOP.Areas.Admin.Controllers
{
    [AdminAuthorize]
    public class AdminUserController : Controller
    {
        EShopEntities db = new EShopEntities();
        //
        // GET: /Admin/AdminUser/

        public ActionResult Index()
        {
            return View();
        }
        public ActionResult AddUser()
        {
            return View();
        }

        public ActionResult UserEmail()
        {
            //lấy những user là khách hàng
            var list = db.UserProfile.Include("webpages_Roles").Where(p => p.webpages_Roles.Where(r => r.RoleId == 1).FirstOrDefault().RoleId == 1).Select(p => new
            {
                UserId = p.UserId,
                UserName = p.UserName,
                Email = p.Email
            }).AsEnumerable();

            List<UserEmail> ue = new List<UserEmail>();
            foreach (var item in list)
            {
                UserEmail temp = new UserEmail() { UserId = item.UserId, UserName = item.UserName, Email = item.Email };
                ue.Add(temp);
            }
            return View(ue);
        }


        public ActionResult LoadEmail()
        {
            string path = Server.MapPath("~/App_Data/emailtemplate.json");
            string json = System.IO.File.ReadAllText(path);
            var data = JsonConvert.DeserializeObject<List<EmailTemplate>>(json);
            return Json(data, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public ActionResult SaveEmail(string ID, string editorEmail)
        {
            try
            {
                string path = Server.MapPath("~/App_Data/emailtemplate.json");
                string jsonStr = System.IO.File.ReadAllText(path);//lấy chuỗi json từ file
                var listemailtemplate = JsonConvert.DeserializeObject<List<EmailTemplate>>(jsonStr);//chuyển chuỗi json thành đối tượng
                foreach (EmailTemplate email in listemailtemplate)
                {
                    if (email.ID == ID)
                    {
                        email.Content = editorEmail;
                        break;
                    }
                }
                jsonStr = JsonConvert.SerializeObject(listemailtemplate, Formatting.Indented);//chuyển đối tượng lại thành chuỗi json
                System.IO.File.WriteAllText(path, jsonStr);
                return Json(new { success = true });
            }
            catch
            {
                return Json(new { success = false });
            }
        }

        [HttpPost]
        public ActionResult AddEmail(string name)
        {
            try
            {
                string path = Server.MapPath("~/App_Data/emailtemplate.json");
                string jsonStr = System.IO.File.ReadAllText(path);
                var listemailtemplate = JsonConvert.DeserializeObject<List<EmailTemplate>>(jsonStr);

                Guid g = Guid.NewGuid();
                string GuidString = Convert.ToBase64String(g.ToByteArray());
                var newemailtemplate = new EmailTemplate() { ID = GuidString, Name = name, Content = "" };
                listemailtemplate.Add(newemailtemplate);

                jsonStr = JsonConvert.SerializeObject(listemailtemplate, Formatting.Indented);
                System.IO.File.WriteAllText(path, jsonStr);
                return Json(new { success = true, ID = GuidString });
            }
            catch
            {
                return Json(new { success = false });
            }
        }

        [HttpPost]
        public ActionResult SendMail(FormCollection fc)
        {
            
            if (fc["editorEmail"] != null && fc["checkedemail"] != null)
            {
                string message = WebUtility.HtmlDecode(fc["editorEmail"]);
                string subject = "Hệ thống TMĐT Eshop - Quảng cáo";
                string[] Emails = fc["checkedemail"].Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                try
                {
                    (new Thread(() =>
                    {

                        foreach (string email in Emails)
                        {
                            doSendmail(message, email, subject);
                        }
                    })).Start();
                }
                catch
                {
                    return RedirectToAction("UserEmail");
                }
                //doSendmail(message, "aaa@gmail.com", "EShop");
            }
            return RedirectToAction("UserEmail");
        }

        private void doSendmail(string message, string emailTo, string subject)
        {
            try
            {
                MailMessage mail = new MailMessage();
                mail.To.Add(new MailAddress(emailTo));
                mail.Subject = subject;
                mail.Body = message;
                mail.IsBodyHtml = true;

                SmtpClient smtp = new SmtpClient();
                smtp.EnableSsl = true;
                smtp.Send(mail);
            }
            catch
            {

            }
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }

    //đối tượng để lưu cấu trúc mẫu mail
    public class EmailTemplate
    {
        public string ID { get; set; }
        public string Name { get; set; }
        public string Content { get; set; }
    }
}
